package org.jeecg.modules.charge.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.entity.basedata.BaseFeeRule;
import org.jeecg.entity.basedata.BaseRoom;
import org.jeecg.entity.basedata.RentContract;
import org.jeecg.entity.charge.*;
import org.jeecg.enums.charge.BillTypeEnum;
import org.jeecg.enums.charge.ChargeComputingTypeEnum;
import org.jeecg.enums.charge.ChargeResidentTypeEnum;
import org.jeecg.modules.charge.entity.ChargeCollect;
import org.jeecg.modules.charge.entity.ChargePringArea;
import org.jeecg.modules.charge.mapper.ChargeBillsMapper;
import org.jeecg.modules.charge.mapper.ChargeInvoiceInfoMapper;
import org.jeecg.modules.charge.mapper.ChargeInvoiceMapper;
import org.jeecg.modules.charge.model.ChargeGenerateModel;
import org.jeecg.modules.charge.service.*;
import org.jeecg.modules.charge.vo.DictModel;
import org.jeecg.service.IFeignBaseDataService;
import org.jeecg.service.IFeignMeterService;
import org.jeecg.vo.charge.ChargeBillsJump;
import org.jeecg.vo.charge.ChargeBillsJumpAll;
import org.jeecg.vo.charge.ChargeMethod;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 账单
 * @Author: jeecg-boot
 * @Date:   2019-08-08
 * @Version: V1.0
 */
@Service
@Slf4j
public class ChargeBillsServiceImpl extends ServiceImpl<ChargeBillsMapper, ChargeBills> implements IChargeBillsService {
    @Autowired
    private ChargeBillsMapper chargeBillsMapper;
    @Autowired
    private ChargeInvoiceMapper chargeInvoiceMapper;
    @Autowired
    private ChargeInvoiceInfoMapper chargeInvoiceinfoMapper;
    @Autowired
    private IChargeDiscountService chargeDiscountService;
    @Autowired
    private IChargeMethodService chargeMethodService;
    @Autowired
    private IChargeBillsHistoryService chargeBillsHistoryService;
    @Autowired
    private IChargeStandardService chargeStandardService;
    @Autowired
    private IChargeFeeitemService chargeFeeitemService;
    @Autowired
    private IChargeBillsMergeService chargeBillsMergeService;
    @Autowired
    private IChargeFeeRuleService chargeFeeRuleService;
    @Autowired
    private IFeignMeterService feignMeterService;
    @Autowired
    private IFeignBaseDataService feignBaseDataService;


    /*
    * 查询业主与房间信息
    * */
    public List<ChargeGenerateModel> getByGenerateCustomer(String projectId,String floorId,String roomName){
        return  chargeBillsMapper.getByGenerateCustomer(projectId,floorId, roomName);
    }

    public Integer updateDiscountMoney(BigDecimal money, String[] ids){
        return chargeBillsMapper.updateDiscountMoney(money, ids);
    }

    @Override
    public List<ChargeBills> getBillsByIds(List<String> ids) {
        return chargeBillsMapper.getBillsByIds(ids);
    }

    @Override
    public List<ChargeBills> queryRoomBills(List roomIdList,String spiltDate) {
        return chargeBillsMapper.queryRoomBills(roomIdList,spiltDate);
    }

    @Override
    public List<ChargeBills> queryContractBills(String contractId){
        return chargeBillsMapper.queryContractBills(contractId);
    }

    @Override
    public List<ChargeBills> findPage(Page<ChargeBills> page, ChargeBills chargeBills) {
        return chargeBillsMapper.findPage(page,chargeBills);
    }

    @Override
    public List<ChargeBills> findList(ChargeBills chargeBills) {
        return chargeBillsMapper.findPage(null,chargeBills);
    }

    @Override
    public void billDelete(String id) {
        chargeBillsMapper.billDelete(id);
    }

    @Override
    public void batchBillDelete(List<String> ids) {
        chargeBillsMapper.batchBillDelete(ids);
    }

    @Override
    public List<ChargeBills> queryRoomAllBills(List<String> roomIdList) {
        return chargeBillsMapper.queryRoomAllBills(roomIdList);
    }

    @Override
    public List<ChargeBills> queryContractAllBills(String contractId,String zjCny) {
        return chargeBillsMapper.queryContractAllBills(contractId,zjCny);
    }

    @Override
    public void canCellAndGenerateRoomBills(List<CanGeBillsVo> cancellBillsVoList) {
        chargeBillsMapper.canCellAndGenerateRoomBills(cancellBillsVoList);
    }

    @Override
    public ChargeBills getMaxPayBills(String roomId) {
        return chargeBillsMapper.getMaxPayBills(roomId);
    }

    @Override
    public void canCellBills(List<String> roomIds, String spiltDate) {
        chargeBillsMapper.canCellBills(roomIds,spiltDate);
    }

    @Override
    public void canCellAllBills(List<String> roomIds) {
        chargeBillsMapper.canCellAllBills(roomIds);
    }

    /*
     * 查询租户与房间信息
     * */
    public List<ChargeGenerateModel> getByGenerateTenant(String projectId,String   floorId,String roomName){
        return  chargeBillsMapper.getByGenerateTenant(projectId,floorId,roomName);
    }

   public String addDate(String time,Integer month) {
        String endDate = "";
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            Date currDate = format.parse(time);
            Calendar ca = Calendar.getInstance();
            ca.setTime(currDate);
            ca.add(Calendar.MONTH, month);
            endDate = format.format(ca.getTime());
        }catch (Exception e){
            log.error("日期转换出错{}",e);
       }
       return endDate;
  }
    /*
     * 账单生成
     * */
    @Transactional(rollbackFor = Exception.class)
    public String createChargeBills(ChargeGenerateBills chargeGenerateBills){
        LoginUser user = SsoUtil.getLoginUser();
        if (StringUtils.isBlank(chargeGenerateBills.getFeeItem())) throw new JeecgBootException("请选择需要生成的收费项!");
        List<String> feeItemIds = Arrays.asList(chargeGenerateBills.getFeeItem().split(","));
        int billsCount = 0;
        if (chargeGenerateBills.getRoomIds().size() <= 0) {
            return "请选择需要生成应收的房间";
        }
        List<String> cnys = new ArrayList<>();  //应收日期列表
        List<BaseRoom> baseRoomList = feignBaseDataService.getByRoomIds(chargeGenerateBills.getRoomIds().toArray(new String[0]),user.getTenantId());
        Map<String,BaseRoom> baseRoomMap = baseRoomList.stream().collect(Collectors.toMap(BaseRoom::getId, Function.identity(), (key1, key2) -> key2));
        List<ChargeFeeitem> feeitemList  =  chargeFeeitemService.list(Wrappers.<ChargeFeeitem>query().lambda().in(ChargeFeeitem::getId,feeItemIds).eq(ChargeFeeitem::getDelFlag,0));
        Map<String,ChargeFeeitem> feeitemMap  = feeitemList.stream().collect(Collectors.toMap(ChargeFeeitem::getId, Function.identity(), (key1, key2) -> key2));
        if(ChargeResidentTypeEnum.CHARGE_RESIDENT_TYPE_TENANT.getCode() == chargeGenerateBills.getResidentType()){ //租户生成账单
             for (String roomId : chargeGenerateBills.getRoomIds()){
                 BaseRoom baseRoom = baseRoomMap.get(roomId);
                 for (String feeItemId:feeItemIds){
                     ChargeFeeitem feeitem = feeitemMap.get(feeItemId);
                    //查询当前房间下绑定的收费标准
                    ChargeStandard chargeStandard = chargeStandardService.getStandardByFeeId(feeItemId,roomId,ChargeResidentTypeEnum.CHARGE_RESIDENT_TYPE_TENANT);
                    if (chargeStandard == null) throw new JeecgBootException(baseRoom.getName() + "房间的租户未设置收费项["+feeitem.getFeeName()+"]对应的收费标准");
                    //费用起始时间是在业主/租户表里,跟收费项没有关系,故列表里每一条的起止收费时间都是一样的
                    //开始时间：租赁开始收费时间   结束时间：租赁合同到期日
                    if (StringUtils.isBlank(chargeStandard.getChargeTime())) { //判断租户是否有开始收费时间 和截止收费日期
                        throw new JeecgBootException(chargeStandard.getRoomName() + "房间的租户未设置初始收费时间");
                    }
                    Date endDate = chargeStandard.getEndDate();
                    if (endDate != null){
                        if (chargeStandard.getStartDate() != null){
                            LocalDate startDate = chargeStandard.getStartDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                            if (startDate.getDayOfMonth() != 1) { //合同开始日期非1号开始,最后截止日期需n-1
                                endDate =  DateUtils.addDate(endDate,-1,"month");
                            }
                        } else {
                            endDate =  DateUtils.addDate(endDate,-1,"month"); //合同开始日期没有的,也按照n-1计算
                        }
                    }
                    if (chargeGenerateBills.getGenerateMode() == 2){ //周期
                        Integer months = chargeGenerateBills.getMonths();
                        String lastBillDate = chargeBillsMapper.getLastGenrateTenantDate(roomId,feeItemId);//最后生成账单日期
                        if (StringUtils.isEmpty(lastBillDate)){
                            chargeGenerateBills.setStartDate(chargeStandard.getChargeTime());
                            //缴费结束日期
                            chargeGenerateBills.setEndDate(addDate(chargeStandard.getChargeTime(), months-1));
                            log.info("1:StartDate:{},EndDate:{},months:{}",chargeGenerateBills.getStartDate(), chargeGenerateBills.getEndDate(), months);
                        }else {
                            chargeGenerateBills.setStartDate(addDate(lastBillDate,1));
                            chargeGenerateBills.setEndDate(addDate(lastBillDate, months));
                            log.info("2:StartDate:{},EndDate:{},months:{}",chargeGenerateBills.getStartDate(), chargeGenerateBills.getEndDate(), months);
                        }
                        //仅按周期生成时,校验合同的结束日(2021-02-04)
                        if (endDate != null){  //结束日期是否大于合同结束日期
                            String endDateStr = DateUtils.date2Str(endDate,DateUtils.date_yymm);
                            if (chargeGenerateBills.getEndDate().compareTo(endDateStr) > 0){
                                chargeGenerateBills.setEndDate(endDateStr);
                            }
                        }
                    }
                    if (chargeGenerateBills.getStartDate().compareTo(chargeStandard.getChargeTime()) < 0) {
                        throw new JeecgBootException(chargeStandard.getRoomName() + "房间账单的生成日期小于初始收费时间");
                    }
                    // 则生成开始和结束日期间的账单
                     log.info("房间生成日期：{}：{}",chargeGenerateBills.getStartDate(), chargeGenerateBills.getEndDate());
                    cnys = DateUtils.getMonthBetween(chargeGenerateBills.getStartDate(), chargeGenerateBills.getEndDate());
                    if (cnys.size() <= 0){
                        throw new JeecgBootException(chargeStandard.getRoomName() + "房间应收账单期为空,请确认收费起止日期!");
                    }
                     //合并收费计算
                    int cycleCounter  = 0; //合并到第几条 计数器
                     StringBuilder mergeBillsId = new StringBuilder();
                     String feeEndDate = "";
                     List<ChargeBillsMerge> chargeBillsMergeList = new ArrayList<>();
                     int baseCycle = 0;
                     if (chargeStandard.getCycle() > 1){
                         baseCycle = chargeStandard.getCycle();
                     }
                    for (String cny : cnys) {
                        billsCount++;
                        ChargeBills bill = new ChargeBills();
                        bill.setId(IdWorker.getIdStr());
                        if ( baseCycle> 1){
                            cycleCounter++;
                            mergeBillsId.append(bill.getId()).append(",");
                            feeEndDate = cny;
                            if (cycleCounter == baseCycle ){
                                ChargeBillsMerge chargeBillsMerge = new ChargeBillsMerge();
                                chargeBillsMerge.setRoomId(roomId);
                                chargeBillsMerge.setFeeitemId(feeItemId);
                                chargeBillsMerge.setFeeEndDate(feeEndDate);
                                chargeBillsMerge.setMergeBillsId(mergeBillsId.toString());
                                chargeBillsMerge.setCycleNum(cycleCounter);
                                chargeBillsMergeList.add(chargeBillsMerge);
                                cycleCounter = 0; //归零
                                mergeBillsId = new StringBuilder();
                            }
                        }
                        bill.setRoomId(roomId);
                        bill.setRentId(chargeStandard.getRentId());
//                        bill.setFeeitemCode(feeitem.getFeeCode());
                        bill.setFeeitemId(feeitem.getId());
                        bill.setCreateBy(user.getId());
                        bill.setCreateTime(new Date());
//                        this.handleDisCount(chargeStandard, bill,chargeGenerateBills.getDisCount());
                        bill.setFeeType(chargeStandard.getComputingType().toString()); // 收费标准的计算方式
                        bill.setFeePrice(Double.parseDouble(chargeStandard.getPrice())); // 计算的单价
                        bill.setZjCny(cny);
                        bill.setProjectId(chargeStandard.getProjectId());
                        bill.setFloorId(chargeStandard.getFloorId());
//                        bill.setRoomProperty(baseRoom.getRoomProperty().toString());
                        bill.setBillsExp(chargeGenerateBills.getBillsExp());
                        try{
                            this.save(bill);
                        }catch (RuntimeException e){
                            throw new JeecgBootException(chargeStandard.getRoomName() + "房间["+feeitem.getFeeName()+"]收费项("+cny+")期已有账单,请勿重复生成！");
                        }
                    }
                    if (cycleCounter > 0 ){
                        ChargeBillsMerge chargeBillsMerge = new ChargeBillsMerge();
                        chargeBillsMerge.setRoomId(roomId);
                        chargeBillsMerge.setFeeitemId(feeItemId);
                        chargeBillsMerge.setFeeEndDate(feeEndDate);
                        chargeBillsMerge.setMergeBillsId(mergeBillsId.toString());
                        chargeBillsMerge.setCycleNum(cycleCounter);
                        chargeBillsMergeList.add(chargeBillsMerge);
                    }
                    if (chargeBillsMergeList.size() > 0){
                        chargeBillsMergeService.saveBatch(chargeBillsMergeList);
                    }
                }
             }
        } else if(ChargeResidentTypeEnum.CHARGE_RESIDENT_TYPE_CUSTOMER.getCode() == chargeGenerateBills.getResidentType()){ //业主生成账单
            for (String roomId : chargeGenerateBills.getRoomIds()) {
                BaseRoom baseRoom = baseRoomMap.get(roomId);
                for (String feeItemId:feeItemIds){
                    ChargeFeeitem feeitem = feeitemMap.get(feeItemId);
                    //查询当前房间下绑定的收费标准
                    ChargeStandard chargeStandard = chargeStandardService.getStandardByFeeId(feeItemId,roomId,ChargeResidentTypeEnum.CHARGE_RESIDENT_TYPE_CUSTOMER);
                    if (chargeStandard == null) throw new JeecgBootException(baseRoom.getName() + "房间的业主未设置收费项["+feeitem.getFeeName()+"]对应的收费标准");
                    if (StringUtils.isBlank(chargeStandard.getChargeTime())) { //判断业主有无初始收费时间
                        throw new JeecgBootException(chargeStandard.getRoomName() + "房间的业主["+ chargeStandard.getRentName() +"]未设置初始收费时间");
                    }
                    Date endDate = chargeStandard.getEndDate();
                    if (endDate != null){
                        if (chargeStandard.getStartDate() != null){
                            LocalDate startDate = chargeStandard.getStartDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                            if (startDate.getDayOfMonth() != 1) { //合同开始日期非1号开始,最后截止日期需n-1
                                endDate =  DateUtils.addDate(endDate,-1,"month");
                            }
                        } else {
                            endDate =  DateUtils.addDate(endDate,-1,"month"); //迁入日期没有的,也按照n-1计算
                        }
                    }
                    // 判断生成账单开始日期是否比开始收费日期大
                    if (chargeGenerateBills.getGenerateMode() == 2) {
                        Integer months = chargeGenerateBills.getMonths();
                        //最后生成账单日期
                        String lastGenrateDate = chargeBillsMapper.getLastGenrateCustomerDate(roomId,feeItemId);
                        if (StringUtils.isEmpty(lastGenrateDate)) {
                            chargeGenerateBills.setStartDate(chargeStandard.getChargeTime());
                            chargeGenerateBills.setEndDate(addDate(chargeStandard.getChargeTime(), months - 1));
                        } else {
                            chargeGenerateBills.setStartDate(addDate(lastGenrateDate,1));
                            chargeGenerateBills.setEndDate(addDate(lastGenrateDate, months));
                        }
                        //仅按周期生成时,校验合同的结束日(2021-02-04)
                        if (endDate != null){  //结束日期是否大于合同结束日期
                            String endDateStr = DateUtils.date2Str(endDate,DateUtils.date_yymm);
                            if (chargeGenerateBills.getEndDate().compareTo(endDateStr) > 0){
                                chargeGenerateBills.setEndDate(endDateStr);
                            }
                        }
                    }
                    if (chargeGenerateBills.getStartDate().compareTo(chargeStandard.getChargeTime()) < 0) {
                        throw new JeecgBootException(chargeStandard.getRoomName() + "房间账单的生成日期小于初始收费时间");
                    }
                    // 则生成开始和结束日期间的账单
                    cnys = DateUtils.getMonthBetween(chargeGenerateBills.getStartDate(), chargeGenerateBills.getEndDate());
                    if (cnys.size() <= 0) {
                        throw new JeecgBootException(chargeStandard.getRoomName() + "房间应收账单期为空,请确认收费起止日期!");
                    }
                    //合并收费计算
                    int cycleCounter  = 0; //合并到第几条 计数器
                    StringBuilder mergeBillsId = new StringBuilder();
                    String feeEndDate = "";
                    List<ChargeBillsMerge> chargeBillsMergeList = new ArrayList<>();
                    int baseCycle = 0; //收费周期
                    if (chargeStandard.getCycle() > 1){
                        baseCycle = chargeStandard.getCycle();
                    }
                    for (String cny : cnys) {
                        billsCount++;
                        ChargeBills bill = new ChargeBills();
                        bill.setId(IdWorker.getIdStr());
                        if (baseCycle > 1){
                            cycleCounter++;
                            mergeBillsId.append(bill.getId()).append(",");
                            feeEndDate = cny;
                            if (cycleCounter == baseCycle ){
                                ChargeBillsMerge chargeBillsMerge = new ChargeBillsMerge();
                                chargeBillsMerge.setRoomId(roomId);
                                chargeBillsMerge.setFeeitemId(feeItemId);
                                chargeBillsMerge.setFeeEndDate(feeEndDate);
                                chargeBillsMerge.setMergeBillsId(mergeBillsId.toString());
                                chargeBillsMerge.setCycleNum(cycleCounter);
                                chargeBillsMergeList.add(chargeBillsMerge);
                                cycleCounter = 0; //归零
                                mergeBillsId = new StringBuilder();
                            }
                        }
                        bill.setRoomId(roomId);
                        bill.setCustomerId(chargeStandard.getRentId());
//                        bill.setFeeitemCode(feeitem.getFeeCode());
                        bill.setFeeitemId(feeitem.getId());
                        bill.setCreateBy(user.getId());
                        bill.setCreateTime(new Date());
//                        this.handleDisCount(chargeStandard,bill,chargeGenerateBills.getDisCount()); //
                        bill.setFeeType(chargeStandard.getComputingType().toString()); // 收费标准的计算方式
                        bill.setFeePrice(Double.parseDouble(chargeStandard.getPrice())); // 计算的单价
                        bill.setZjCny(cny);
                        bill.setProjectId(chargeStandard.getProjectId());
                        bill.setFloorId(chargeStandard.getFloorId());
//                        bill.setRoomProperty(baseRoom.getRoomProperty().toString());
                        bill.setBillsExp(chargeGenerateBills.getBillsExp());
                        try{
                            this.save(bill);
                        }catch (RuntimeException e){
                            // 由唯一键校验 生成账单，需要判断此业主ID下这个收费标准下，这个月里是否有账单，没有则生成，有就跳出
                            throw new JeecgBootException(chargeStandard.getRoomName() + "房间收费项["+feeitem.getFeeName()+"]("+cny+")期已有账单,请勿重复生成！");
                        }
                    }
                    if (cycleCounter > 0 ){
                        ChargeBillsMerge chargeBillsMerge = new ChargeBillsMerge();
                        chargeBillsMerge.setRoomId(roomId);
                        chargeBillsMerge.setFeeitemId(feeItemId);
                        chargeBillsMerge.setFeeEndDate(feeEndDate);
                        chargeBillsMerge.setMergeBillsId(mergeBillsId.toString());
                        chargeBillsMerge.setCycleNum(cycleCounter);
                        chargeBillsMergeList.add(chargeBillsMerge);
                    }
                    if (chargeBillsMergeList.size() > 0){
                        chargeBillsMergeService.saveBatch(chargeBillsMergeList);
                    }
                }
            }
        }
        return "账单生成,合计生成:" + billsCount + "个;";
    }

    /**
     * 账单生成 合同管理 - 改版
     * @param chargeGenerateBills
     */
    @Override
    public Result<String> createChargeBillsContractNew(ChargeGenerateBills chargeGenerateBills) {
        int billsCount = 0; //生成的账单总数
        //查询收费规则
        BaseFeeRule feeRule = chargeBillsMapper.getBaseFeeRuleById(chargeGenerateBills.getFeeRuleId());
        if (feeRule == null) return Result.error("收费规则系统中不存在!");
        List<RentContract> rentContractList = chargeBillsMapper.getByContractIds(chargeGenerateBills.getContractIds().toArray(new String[0]));
        Map<String, RentContract> baseContractMap = rentContractList.stream().collect(Collectors.toMap(RentContract::getId, Function.identity(), (key1, key2) -> key2));
        for (String contractId : chargeGenerateBills.getContractIds()) {
            RentContract rentContract = baseContractMap.get(contractId);
            if (rentContract.getStartDate() == null) {
                return Result.error(rentContract.getName() + "合同初始收费时间为空!");
            }
            //计算生成账单的起止日期
            if (chargeGenerateBills.getGenerateMode() == 1) { //按照指定月份
                String startDate = DateUtils.date2Str(rentContract.getStartDate(), DateUtils.date_yymm);
                if (chargeGenerateBills.getStartDate().compareTo(startDate) < 0) {
                    return Result.error(rentContract.getName() + "合同账单的生成日期小于初始收费时间!");
                }
            } else if (chargeGenerateBills.getGenerateMode() == 2) { //按照周期
                Integer months = chargeGenerateBills.getMonths();
                //  todo 租赁住户都是查询房间？？？
                String lastBillDate = chargeBillsMapper.getLastBillDate(contractId, feeRule.getFeeId());//最后生成账单日期
                if (StringUtils.isEmpty(lastBillDate)) {
                    Date startDate = rentContract.getStartDate();
                    //判断收费规则当月是否收费
                    if (!feeRule.getIsFirstFee()) { //当月不收费
                        startDate = DateUtils.addDate(rentContract.getStartDate(), 1, "month");
                    }
                    chargeGenerateBills.setStartDate(DateUtils.date2Str(startDate, DateUtils.date_yymm));
                    chargeGenerateBills.setEndDate(addDate(chargeGenerateBills.getStartDate(), months - 1)); //缴费结束日期
                    log.info("1:StartDate:{},EndDate:{},months:{}", chargeGenerateBills.getStartDate(), chargeGenerateBills.getEndDate(), months);
                } else {
                    chargeGenerateBills.setStartDate(addDate(lastBillDate, 1));
                    chargeGenerateBills.setEndDate(addDate(lastBillDate, months));
                    log.info("2:StartDate:{},EndDate:{},months:{}", chargeGenerateBills.getStartDate(), chargeGenerateBills.getEndDate(), months);
                }
            }
                //最多可预生成3年的账单 TODO
                List<String> cnyList = DateUtils.getMonthBetween(chargeGenerateBills.getStartDate(), chargeGenerateBills.getEndDate());
                if (cnyList.size() <= 0) {
                    return Result.error(rentContract.getName() + "合同计算后的应收账单期为空,请确认收费起止日期!");
                }
                //合并收费计算
                int cycleCounter = 0; //合并到第几条 计数器
                StringBuilder mergeBillsId = new StringBuilder();
                String feeEndDate = "";
                List<ChargeBillsMerge> chargeBillsMergeList = new ArrayList<>();
                int baseCycle = 0;
                if (feeRule.getCycle() > 1) {
                    baseCycle = feeRule.getCycle();
                }
                for (String cny : cnyList) {
                    billsCount++;
                    ChargeBills bill = new ChargeBills();
                    bill.setId(IdWorker.getIdStr());
                    if (baseCycle > 1) {
                        cycleCounter++;
                        mergeBillsId.append(bill.getId()).append(",");
                        feeEndDate = cny;
                        if (cycleCounter == baseCycle) {
                            ChargeBillsMerge chargeBillsMerge = new ChargeBillsMerge();
                            chargeBillsMerge.setRoomId(rentContract.getRoomId());
                            chargeBillsMerge.setContractId(contractId);
                            chargeBillsMerge.setFeeitemId(feeRule.getFeeId());
                            chargeBillsMerge.setFeeEndDate(feeEndDate);
                            chargeBillsMerge.setMergeBillsId(mergeBillsId.toString());
                            chargeBillsMerge.setCycleNum(cycleCounter);
                            chargeBillsMergeList.add(chargeBillsMerge);
                            cycleCounter = 0; //归零
                            mergeBillsId = new StringBuilder();
                        }
                    }
                    bill.setRoomId(rentContract.getRoomId());
                    bill.setContractId(contractId);
                    bill.setFeeitemId(feeRule.getFeeId());
                    this.handleDisCount(feeRule, bill, chargeGenerateBills.getDisCount(),rentContract.getBuildArea()); //折扣账单
                    bill.setFeeType(feeRule.getComputingType().toString()); // 收费标准的计算方式
                    bill.setFeePrice(feeRule.getPrice().doubleValue()); // 计算的单价
                    bill.setZjCny(cny);
                    bill.setProjectId(rentContract.getProjectId());
                    bill.setFloorId(rentContract.getFloorId());
                    bill.setRemarks(chargeGenerateBills.getBillsExp());
                    try {
                        this.save(bill);
                    } catch (RuntimeException e) {
                        throw new JeecgBootException(rentContract.getName() + "合同[" + feeRule.getName() + "](" + cny + ")期已有账单,请勿重复生成！");
                    }
                }
                if (cycleCounter > 0) {
                    ChargeBillsMerge chargeBillsMerge = new ChargeBillsMerge();
                    chargeBillsMerge.setRoomId(rentContract.getRoomId());
                    chargeBillsMerge.setContractId(contractId);
                    chargeBillsMerge.setFeeitemId(feeRule.getFeeId());
                    chargeBillsMerge.setFeeEndDate(feeEndDate);
                    chargeBillsMerge.setMergeBillsId(mergeBillsId.toString());
                    chargeBillsMerge.setCycleNum(cycleCounter);
                    chargeBillsMergeList.add(chargeBillsMerge);
                }
                if (chargeBillsMergeList.size() > 0) {
                    chargeBillsMergeService.saveBatch(chargeBillsMergeList);
                }
        }
        return Result.ok("账单生成,合计生成:" + billsCount + "个;");
    }

    /**
     * 账单生成 - 改版
     * @param chargeGenerateBills
     */
    @Override
    public Result<String> createChargeBillsNew(ChargeGenerateBills chargeGenerateBills) {
        int billsCount = 0; //生成的账单总数
        LoginUser loginUser = SsoUtil.getLoginUser();
        String tenantId = "";
        if (null == loginUser){
            tenantId = chargeGenerateBills.getTenantId();
        }else {
            tenantId = loginUser.getTenantId();
        }
        //查询收费规则
        ChargeFeeRule feeRule = chargeFeeRuleService.getById(chargeGenerateBills.getFeeRuleId());
        if (feeRule == null) return Result.error("收费规则系统中不存在!");
        List<BaseRoom> baseRoomList = feignBaseDataService.getByRoomIds(chargeGenerateBills.getRoomIds().toArray(new String[0]),tenantId);
        Map<String,BaseRoom> baseRoomMap = baseRoomList.stream().collect(Collectors.toMap(BaseRoom::getId, Function.identity(), (key1, key2) -> key2));
        String startDateStr = chargeGenerateBills.getStartDate();
        String endDateStr = chargeGenerateBills.getEndDate();
        for (String roomId : chargeGenerateBills.getRoomIds()){
            BaseRoom room  = baseRoomMap.get(roomId);
            if (room.getFeeStartDate() == null){
                return Result.error(room.getName() + "房间初始收费时间为空!");
            }
            //计算生成账单的起止日期
            if (chargeGenerateBills.getGenerateMode() == 1){ //按照指定月份
                /*
                String startDate = DateUtils.date2Str(room.getFeeStartDate(),DateUtils.date_yymm);
                if (chargeGenerateBills.getStartDate().compareTo(startDate) < 0){
                    return Result.error(room.getName() + "房间账单的生成日期小于初始收费时间!");
                }
                 */
                if (StringUtils.isBlank(startDateStr)) {
                    String lastBillDate = chargeBillsMapper.getLastBillDate(roomId,feeRule.getFeeId());
                    // 判断结束时间
                    if (StringUtils.isBlank(lastBillDate)) {
                        startDateStr = DateUtils.date2Str(room.getFeeStartDate(), DateUtils.date_yymm);
                    } else {
                        startDateStr = addDate(lastBillDate, 1);
                    }
                }
            } else if (chargeGenerateBills.getGenerateMode() == 2){ //按照周期
                Integer months = chargeGenerateBills.getMonths();
                String lastBillDate = chargeBillsMapper.getLastBillDate(roomId,feeRule.getFeeId());//最后生成账单日期
                if (StringUtils.isEmpty(lastBillDate)){
                    Date startDate = room.getFeeStartDate();
                    //判断收费规则当月是否收费
                    if (!feeRule.getIsFirstFee()){ //当月不收费
                        startDate =  DateUtils.addDate(room.getFeeStartDate(),1,"month");
                    }
                    startDateStr = DateUtils.date2Str(startDate,DateUtils.date_yymm);

                    chargeGenerateBills.setEndDate(addDate(chargeGenerateBills.getStartDate(), months-1)); //缴费结束日期
                    log.info("1:StartDate:{},EndDate:{},months:{}",chargeGenerateBills.getStartDate(), chargeGenerateBills.getEndDate(), months);
                }else {
                    startDateStr = addDate(lastBillDate,1);

                    chargeGenerateBills.setEndDate(addDate(lastBillDate, months));
                    log.info("2:StartDate:{},EndDate:{},months:{}",chargeGenerateBills.getStartDate(), chargeGenerateBills.getEndDate(), months);
                }
            }
            if (endDateStr.compareTo(startDateStr) < 0) {
                return Result.error(room.getName() + "房间开始收费时间不能大于结束收费时间!");
            }
            //最多可预生成3年的账单 TODO
            List<String> cnyList = DateUtils.getMonthBetween(startDateStr, chargeGenerateBills.getEndDate());
            if (cnyList.size() <= 0){
                return Result.error(room.getName()+ "房间计算后的应收账单期为空,请确认收费起止日期!");
            }
            //合并收费计算
            int cycleCounter  = 0; //合并到第几条 计数器
            StringBuilder mergeBillsId = new StringBuilder();
            String feeEndDate = "";
            List<ChargeBillsMerge> chargeBillsMergeList = new ArrayList<>();
            int baseCycle = 0;
            if (feeRule.getCycle() > 1){
                baseCycle = feeRule.getCycle();
            }
            for (String cny : cnyList) {
                billsCount++;
                ChargeBills bill = new ChargeBills();
                bill.setId(IdWorker.getIdStr());
                if ( baseCycle> 1){
                    cycleCounter++;
                    mergeBillsId.append(bill.getId()).append(",");
                    feeEndDate = cny;
                    if (cycleCounter == baseCycle ){
                        ChargeBillsMerge chargeBillsMerge = new ChargeBillsMerge();
                        chargeBillsMerge.setRoomId(roomId);
                        chargeBillsMerge.setFeeitemId(feeRule.getFeeId());
                        chargeBillsMerge.setFeeEndDate(feeEndDate);
                        chargeBillsMerge.setMergeBillsId(mergeBillsId.toString());
                        chargeBillsMerge.setCycleNum(cycleCounter);
                        chargeBillsMergeList.add(chargeBillsMerge);
                        cycleCounter = 0; //归零
                        mergeBillsId = new StringBuilder();
                    }
                }
                bill.setRoomId(roomId);
                bill.setFeeitemId(feeRule.getFeeId());
                this.handleDisCount(feeRule, bill,chargeGenerateBills.getDisCount(),room.getBuildArea()); //折扣账单
                bill.setFeeType(feeRule.getComputingType().toString()); // 收费标准的计算方式
                bill.setFeePrice(feeRule.getPrice().doubleValue()); // 计算的单价
                bill.setZjCny(cny);
                bill.setProjectId(room.getProjectId());
                bill.setFloorId(room.getFloorId());
                bill.setRemarks(chargeGenerateBills.getBillsExp());
                try{
                    this.save(bill);
                }catch (RuntimeException e){
                    throw new JeecgBootException(room.getName() + "房间["+feeRule.getName()+"]("+cny+")期已有账单,请勿重复生成！");
                }
            }
            if (cycleCounter > 0 ){
                ChargeBillsMerge chargeBillsMerge = new ChargeBillsMerge();
                chargeBillsMerge.setRoomId(roomId);
                chargeBillsMerge.setFeeitemId(feeRule.getFeeId());
                chargeBillsMerge.setFeeEndDate(feeEndDate);
                chargeBillsMerge.setMergeBillsId(mergeBillsId.toString());
                chargeBillsMerge.setCycleNum(cycleCounter);
                chargeBillsMergeList.add(chargeBillsMerge);
            }
            if (chargeBillsMergeList.size() > 0){
                chargeBillsMergeService.saveBatch(chargeBillsMergeList);
            }
        }
        return Result.ok("账单生成,合计生成:" + billsCount + "个;");
    }

    /**
     * 处理计算 - 折扣账单
     * @param feeRule 收费规则
     * @param bill 账单
     * @param disCount 折扣
     * @param buildArea 房间面积
     */
    private void handleDisCount(ChargeFeeRule feeRule, ChargeBills bill,Double disCount,BigDecimal buildArea) {
        BigDecimal feeCurrent = feeRule.getPrice(); //标准应收金额
        if (feeRule.getComputingType() == ChargeComputingTypeEnum.CHARGE_COMPUTING_TYPE_PRICE.getCode()){
            feeCurrent = feeCurrent.multiply(buildArea);
        }
        if (null != disCount) {// 判断是否打折模式
            feeCurrent = feeCurrent.multiply(new BigDecimal(disCount)).divide(new BigDecimal(10)); //折扣后金额
            bill.setBillType(BillTypeEnum.BILL_TYPE_REDUCED.getCode());//折扣账单
            bill.setPayReduced(feeRule.getPrice().subtract(feeCurrent));//优惠金额 = 收费项金额 - 折扣后金额
        }
        feeCurrent = feeCurrent.setScale(2, BigDecimal.ROUND_HALF_UP); //精度计算
        if(feeRule.getUnitAccount() != null){
            feeCurrent = feeCurrent.setScale(feeRule.getUnitAccount(), BigDecimal.ROUND_HALF_UP);
        }
        bill.setDue(feeCurrent);
    }

    public List<ChargeBills> getFeeItemId(List<String> ids){
        return chargeBillsMapper.getFeeItemId(ids);
    }

    /*合并账单进行跳转*/
    public List<ChargeBillsJump> getByChargeBills(List<String> ids){
        List<ChargeBillsJump> billsList = chargeBillsMapper.getByChargeBills(ids);
        List<ChargeBillsJump> billsLists = new ArrayList<ChargeBillsJump>();// 账单集合
        for (ChargeBillsJump bills : billsList) {
            bills.setNum(1);
            String cny = bills.getZjCny();
            String billsid = bills.getId();
            boolean flag = false;
            for (ChargeBillsJump utils : billsLists) {
                if(utils != null){
                    if (bills.getFeeitemId().equals(utils.getFeeitemId())
                            && Double.doubleToLongBits(bills.getZjJe()) == Double.doubleToLongBits(utils.getZjJe())) { // 判断是否有相同的收费项目和金额
                        billsid += "," + utils.getId();
                        cny += "," + utils.getZjCny();
                        utils.setZjCny(cny);
                        utils.setNum(utils.getNum() + 1);
                        utils.setId(billsid);
                        flag = true;
                    }
                }
            }
            if (!flag) {
                billsLists.add(bills);
            }
        }
        for (ChargeBillsJump billss : billsLists) {
            if(billss.getZjJe() > 0 && billss.getNum() > 0){
                billss.setFeePrice(billss.getZjJe());
                BigDecimal b = new BigDecimal(billss.getZjJe() * billss.getNum());
                Double  money = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                billss.setZjJe(money);
                if(billss.getTaxRate() != null && billss.getTaxRate() > 0){
                    BigDecimal se = new BigDecimal(money - money/(1 + billss.getTaxRate() / 100));
                    Double tax = se.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    billss.setTaxPaid(tax);
                }
            }
            billss.setUnit("月");
            String[] zjCny = billss.getZjCny().split(",");
            StringUtils.buffSort(zjCny);
            billss.setZjCny(zjCny[0] + ">" + zjCny[zjCny.length - 1]);
            billss.setIsDay("1");
        }
        return  billsLists;
    }
    @Override
    public List<ChargeBills> listById(String[] ids) {
        return chargeBillsMapper.listById(ids);
    }

    @Override
    public List<ChargeBills> listByBills(List<String> ids) {
        return chargeBillsMapper.listByBills(ids);
    }

    public ChargeBillsJumpAll getByChargeBillsAll(List<String> ids){
        LoginUser sysUser = SsoUtil.getLoginUser();
        List<ChargeBillsJump> billsLists = new ArrayList<ChargeBillsJump>();// 账单集合
        List<ChargeBillsJump> billsList = new ArrayList<ChargeBillsJump>();
        Set<String> addSet=new HashSet<String>();//地址
         ChargeBillsJumpAll billsJumpAll = new ChargeBillsJumpAll();
        Double sumMoney = 0.0;
        Double sumTaxPaid = 0.0;
        Double discount = 0.0;
        if(ids != null && ids.size() > 0) {
            billsList = chargeBillsMapper.getByChargeBills(ids);
            for (ChargeBillsJump bills : billsList) {
                String cny = bills.getZjCny();
                bills.setNum(1);
                boolean flag = false;
                for (ChargeBillsJump utils : billsLists) {
                    if (utils == null) continue;
                    // 判断是否有相同的收费项目和金额
                    if (bills.getFeeitemId().equals(utils.getFeeitemId())
                            && Double.doubleToLongBits(bills.getZjJe()) == Double.doubleToLongBits(utils.getZjJe())) {
                        utils.setNum(utils.getNum() + 1);
                        flag = true;
                    }
                }
                if (!flag) {
                    billsLists.add(bills);
                }
            }
            for (ChargeBillsJump billss : billsLists) {
                addSet.add(billss.getAddress());
                if (billss.getZjJe() > 0 && billss.getNum() > 0) {
                    BigDecimal b = new BigDecimal(billss.getZjJe() * billss.getNum());
                    Double money = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    sumMoney += money;
                    if (billss.getTaxRate() > 0) {
                        BigDecimal se = new BigDecimal(money - money / (1 + billss.getTaxRate() / 100));
                        Double tax = se.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        sumTaxPaid += tax;
                    }
                }
            }
        }
        //计算优惠信息
        for (ChargeBillsJump billsJump: billsList){
            //查找优惠信息
            ChargeDiscount cd = new ChargeDiscount();
            cd.setProjectId(billsJump.getProjectId());
            cd.setFeeId(billsJump.getFeeitemId());
//            cd.setFeeCode(billsJump.getFeeitemCode());
            ChargeDiscount chargeDiscount = chargeDiscountService.getDiscount(cd);
            //优惠信息
            if (chargeDiscount != null){
                //是否满足优惠条件
                if (billsJump.getNum() >= chargeDiscount.getMonths() && chargeDiscount.getDiscountScale() > 0 &&
                        ("1").equals(chargeDiscount.getIsAgain())){
                    //实付金额 = 应付金额 * 折扣
                    BigDecimal actualAmount = new BigDecimal(billsJump.getZjJe()).multiply(new BigDecimal(chargeDiscount.getDiscountScale() / (10)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    //优惠金额 = 应收 - 实付
                    BigDecimal disAmount = new BigDecimal(billsJump.getZjJe()).subtract(actualAmount);
                    //由于原逻辑处理合并订单只有一个订单num为累加。其他还是为1，故对合并优惠 * num
                    discount += disAmount.doubleValue() * billsJump.getNum();
                }
            }
        }
        Double sumIncome = 0.0;
        if (discount > 0){
            BigDecimal d = new BigDecimal(discount);
            discount = d.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        if(sumMoney > 0){
            BigDecimal b = new BigDecimal(sumMoney);
            sumMoney = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        if(sumTaxPaid > 0){
            BigDecimal b = new BigDecimal(sumTaxPaid);
            sumTaxPaid = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        //todo 单条税率为0时总计金额有问题，税额可以为0？？？？
        if(sumMoney > 0 && sumTaxPaid > 0){
            //合计收入 = 总金额 - 优惠 - 税额
            BigDecimal b = new BigDecimal(sumMoney  - discount - sumTaxPaid);
            sumIncome = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        billsJumpAll.setSumMoney(sumMoney);
        billsJumpAll.setDiscount(discount);
        billsJumpAll.setSumTaxPaid(sumTaxPaid);
        billsJumpAll.setSumIncome(sumIncome);
        if(addSet.size() > 0){
            billsJumpAll.setAddress(String.join(",", addSet));
        }
        billsJumpAll.setPayuserId(sysUser.getId());
        billsJumpAll.setPayuserName(sysUser.getRealname());
        List<ChargeMethod> payTypeList = chargeMethodService.getPayMethodList(0,SsoUtil.getLoginUser().getTenantId());
        billsJumpAll.setPayTypeList(payTypeList);
        return  billsJumpAll;
    }

    public ChargeBillsJumpAll getMethodUser(){
        LoginUser sysUser = SsoUtil.getLoginUser();
        ChargeBillsJumpAll billsJumpAll = new ChargeBillsJumpAll();
        billsJumpAll.setPayuserId(sysUser.getId());
        billsJumpAll.setPayuserName(sysUser.getRealname());
        List<ChargeMethod> payTypeList = chargeMethodService.getPayMethodList(0,sysUser.getTenantId());
        billsJumpAll.setPayTypeList(payTypeList);
        return  billsJumpAll;
    }


    public ChargeFeeitem getByFeeCode(String  feeCode, String projectId){
        return chargeBillsMapper.getByFeeCode(feeCode,projectId);
    }

    @Override
    public Integer updateBills(ChargeBills bills) {
        LoginUser sysUser = SsoUtil.getLoginUser();
        bills.setUpdateBy(sysUser.getId());
        bills.setUpdateTime(new Date());
        return chargeBillsMapper.updateBills(bills);
    }

    @Override
    public Integer updateBillsBatch(List<ChargeBills> billsList) {
        return chargeBillsMapper.updateBillsBatch(billsList);
    }


    public  List<DictModel> getRoomproperty(){
        List<DictModel> method = chargeBillsMapper.getRoomproperty();
        return method;
    }


    /***=======================================================================================================================================-=======================================
     *
     *   账单退款
     *  由订单处进行退款
     * */
    @Deprecated
    public Integer refund(ChargeBills bills){
        LoginUser loginUser = SsoUtil.getLoginUser();
        Integer result = 0;
        try{
            if(null != bills && StringUtils.isNotEmpty(bills.getId())) {
                ChargeBills utilbills =  chargeBillsMapper.get(bills.getId());//账单对象
                List<ChargeBills>  billslist= chargeBillsMapper.getBillsByInvoiceNo(utilbills.getInvoiceNo(),utilbills.getInvoiceGrnno());
                if(billslist.size() > 0 && bills.getStatus().equals("1")){
                    for(ChargeBills utils :billslist){
                        //修改原有账单与生成负数账单  查询生成账单对象
                        ChargeBills utilBills = new ChargeBills();
                        ChargeBills refundBills = new ChargeBills();//退款账单
                        //退款旧账单
                        utils.setZjTkrq(bills.getZjTkrq());
                        utils.setBillsExp("已退款");
                        result += chargeBillsMapper.updateyOneUtily(utils);
                        //重新生成退款账单表
                        refundBills.setId(String.valueOf(IdWorker.getId()));
                        refundBills.setZjTksm(bills.getZjTksm());
//                        refundBills.setZjJe(utils.getZjJe() == null ?0:0-utils.getZjJe());
                        refundBills.setInvoiceNo(bills.getInvoiceNo());
                        refundBills.setInvoiceGrnno(bills.getInvoiceGrnno());
                        refundBills.setZjTzrq(null);
                        refundBills.setZjSkrq(bills.getZjTkrq());
                        refundBills.setProjectId(utils.getProjectId());
                        refundBills.setZjTkhm(utils.getId());
                        refundBills.setCreateTime(new Date());
                        refundBills.setCreateBy(loginUser.getId());
                        refundBills.setUpdateTime(new Date());
                        refundBills.setUpdateBy(loginUser.getId());
                        refundBills.setCustomerId(utils.getCustomerId());
                        refundBills.setRentId(utils.getRentId());
                        refundBills.setZjCny(utils.getZjCny());
//                        refundBills.setFeeitemCode(utils.getFeeitemCode());
                        refundBills.setFeeitemId(utils.getFeeitemId());
                        refundBills.setPayuserName(utils.getPayuserName());
//                        refundBills.setRoomProperty(utils.getRoomProperty());
                        refundBills.setPayType(utils.getPayType());
                        refundBills.setMakeinvoiceDate(utils.getMakeinvoiceDate());
                        chargeBillsMapper.insertBills(refundBills); //插入退款的负数账单
                       //生成应收账单
                        utilBills = chargeBillsMapper.get(utils.getId());//生成账单对象
                        utilBills.setId(String.valueOf(IdWorker.getId()));
                        utilBills.setZjSkrq(null);
                        utilBills.setPayuserName(null);
                        utilBills.setZjTkrq(null);
                        utilBills.setZjTzrq(null);
                        utilBills.setPayType(null);
                        utilBills.setInvoiceNo(null);
                        utilBills.setInvoiceGrnno(null);
                        utilBills.setMakeinvoiceDate(null);
                        utilBills.setBillsExp("退款生成应收账单");
                        utilBills.setIncome(null);
                        utilBills.setTaxPaid(0.0);
                        utilBills.setTaxRate(0.0);
//                        utilBills.setZjJe(utils.getZjJe());
                        chargeBillsMapper.insertBills(utilBills);
                         /*历史记录插入退款账单信息*/
                        List<ChargeBills> list = new ArrayList<ChargeBills>();
                        utils.setParentBillsIds(utilBills.getId());
                        refundBills.setParentBillsIds(utilBills.getId());
                        list.add(utils);
                        list.add(refundBills);
                        chargeBillsMapper.insertListHistory(list);
                    }
                }else{
                    /**
                     * 无票据账单退款以及单条账单进行退款
                     * */
                    ChargeBills utilBills = new ChargeBills();//新账单
                    ChargeBills refundBills = new ChargeBills();//退款账单
                    //退款旧账单
                    utilbills.setZjTkrq(bills.getZjTkrq());
                    utilbills.setBillsExp("已退款");
                    result += chargeBillsMapper.updateyOneUtily(utilbills);
                    //重新生成退款账单
                    refundBills.setId(String.valueOf(IdWorker.getId()));
                    refundBills.setZjTksm(bills.getZjTksm());
                    refundBills.setFeeitemId(utilbills.getFeeitemId());
//                    refundBills.setFeeitemCode(utilbills.getFeeitemCode());
//                    refundBills.setRoomProperty(utilbills.getRoomProperty());
                    refundBills.setTaxPaid(utilbills.getTaxPaid() == null ?0:0-utilbills.getTaxPaid());
                    refundBills.setInvoiceNo(bills.getInvoiceNo());
                    refundBills.setInvoiceGrnno(bills.getInvoiceGrnno());
                    refundBills.setZjSkrq(bills.getZjTkrq());
                    refundBills.setMakeinvoiceDate(bills.getZjTkrq());
                    refundBills.setZjTkhm(utilbills.getId());
                    refundBills.setCustomerId(utilbills.getCustomerId());
                    refundBills.setRentId(utilbills.getRentId());
                    refundBills.setZjCny(utilbills.getZjCny());
                    refundBills.setPayType(bills.getPayType());
                    if(bills.getStatus().equals("0") && bills.getStatusAll().equals("0")){
                        refundBills.setDue(BigDecimal.ZERO.subtract(bills.getDue()));
                    }else{
                        refundBills.setDue(BigDecimal.ZERO.subtract(utilbills.getDue()));
                    }
                    chargeBillsMapper.insertBills(refundBills);
                    utilBills = chargeBillsMapper.get(bills.getId());//生成账单对象
                    //生成账单
                    utilBills.setId(String.valueOf(IdWorker.getId()));
                    utilBills.setZjSkrq(null);
                    utilBills.setPayuserName(null);
                    if(bills.getStatus().equals("0") && bills.getStatusAll().equals("0")){
                        BigDecimal big = utilBills.getDue().subtract(bills.getDue());
                        utilBills.setDue(big.setScale(1, BigDecimal.ROUND_HALF_UP));
                    }
                    utilBills.setZjTkrq(null);
                    utilBills.setZjTzrq(null);
                    utilBills.setPayType(null);
                    utilBills.setInvoiceNo(null);
                    utilBills.setInvoiceGrnno(null);
                    utilBills.setMakeinvoiceDate(null);
                    utilBills.setBillsExp("退款生成应收账单");
                    utilBills.setIncome(null);
                    utilBills.setTaxPaid(0.0);
                    utilBills.setTaxRate(0.0);
                    chargeBillsMapper.insertBills(utilBills);
                    /*历史记录插入退款账单信息*/
                    List<ChargeBills> list = new ArrayList<ChargeBills>();
                    utilbills.setParentBillsIds(utilBills.getId());
                    refundBills.setParentBillsIds(utilBills.getId());
                    list.add(utilbills);
                    list.add(refundBills);
                    chargeBillsMapper.insertListHistory(list);
                }

                /**
                 * 票据表信息插入
                 * */
                if(billslist.size() > 0 && bills.getStatus().equals("1")){
                    //原账单的票据信息
                    ChargeInvoice invoice = chargeInvoiceMapper.getInvoiceDmHm(utilbills.getInvoiceNo(),utilbills.getInvoiceGrnno());
                    //原账单的票据详细信息
                    List<ChargeInvoiceInfo> infolist = chargeInvoiceinfoMapper.getInvoiceInfo(invoice.getId());
                    invoice.setTax(0-invoice.getTax());
                    invoice.setMoney(0-invoice.getMoney());
                    invoice.setPayMethod(bills.getPayType());
                    invoice.setZjSkrq(bills.getZjTkrq());
                    invoice.setProjectId(utilbills.getProjectId());
                    invoice.setCustomerId(utilbills.getCustomerId());
                    invoice.setUpdateBy(loginUser.getId());
                    invoice.setUpdateDate(new Date());
                    invoice.setInvoiceDm(bills.getInvoiceGrnno());
                    invoice.setInvoiceHm(bills.getInvoiceNo());
                    String pjId = chargeInvoiceMapper.getIdByInvoice(bills.getInvoiceNo(), bills.getInvoiceGrnno());//获取最新退款票据
                    invoice.setId(pjId);
                    Integer up = chargeInvoiceMapper.updateById(invoice); //票据表插入退款账单票据
                    List<ChargeInvoiceInfo> infos = new ArrayList<ChargeInvoiceInfo>();
                   for(ChargeInvoiceInfo info:infolist){
                       info.setId(String.valueOf(IdWorker.getId()));
                        info.setInvoiceDm(bills.getInvoiceGrnno());
                        info.setInvoiceHm(bills.getInvoiceNo());
                        info.setUnitPrice(0-info.getUnitPrice());
                        info.setRate(info.getRate());
                        info.setTax(0-info.getTax());
                        info.setMoney(0-info.getMoney());
                        info.setInvoiceId(pjId);
                        info.setRealMoney(0 - info.getRealMoney());
                        info.setRealPrice(0 - info.getRealPrice());
                        info.setIsDeposit("1");
                        info.setDelFlag("0");
                        info.setCreateBy(loginUser.getId());
                        info.setCreateDate(new Date());
                        infos.add(info);
                    }
                    if(infos.size() >0){
                        chargeInvoiceinfoMapper.insertInfos(infos);//票据详情表插入退款账单详情
                    }
                }else{
                    //无票据账单退款添加票据
                    ChargeInvoice invoice = new ChargeInvoice();
                    invoice.setTax(0.0);
                    if(bills.getStatus().equals("0") && bills.getStatusAll().equals("0")){
                        invoice.setMoney(BigDecimal.ZERO.subtract(bills.getDue()).doubleValue());
                    }else{
                        invoice.setMoney(utilbills.getDue().doubleValue());
                    }
                    invoice.setMakeInvoiceDate(bills.getZjTkrq());
                    invoice.setPayMethod(bills.getPayType());
                    invoice.setZjSkrq(bills.getZjTkrq());
                    invoice.setProjectId(utilbills.getProjectId());
                    invoice.setCustomerId(utilbills.getCustomerId());
                    invoice.setUpdateBy(loginUser.getId());
                    invoice.setUpdateDate(new Date());
                    String pjId = chargeInvoiceMapper.getIdByInvoice(bills.getInvoiceNo(), bills.getInvoiceGrnno());//获取最新退款票据
                    invoice.setId(pjId);
                    Integer up = chargeInvoiceMapper.updateById(invoice); //票据表插入退款账单票据
                    //无票据账单退款添加票据详情
                    List<ChargeInvoiceInfo> infos = new ArrayList<ChargeInvoiceInfo>();
                    ChargeInvoiceInfo info = new ChargeInvoiceInfo();
                    info.setId(String.valueOf(IdWorker.getId()));
                    info.setInvoiceDm(bills.getInvoiceGrnno());
                    info.setInvoiceHm(bills.getInvoiceNo());
                    info.setInvoiceObject(utilbills.getFeeName());
                    info.setNum(1);
                    info.setUnitPrice(0.0);
                    info.setRate(0.0);
                    info.setTax(0.0);
                    if(bills.getStatus().equals("0") && bills.getStatusAll().equals("0")){
                        info.setMoney(BigDecimal.ZERO.subtract(bills.getDue()).doubleValue());
                    }else{
                        info.setMoney(utilbills.getDue().doubleValue());
                    }
                    info.setAbstractInfo(utilbills.getZjCny());
                    info.setInvoiceId(pjId);
                    info.setFeeitemId(utilbills.getFeeitemId());
                    // 0:表示日常收费
                    info.setIsDay("0");
                    info.setRealMoney(utilbills.getTaxPaid());
                    info.setRealPrice( utilbills.getTaxPaid());
                    infos.add(info);
                    chargeInvoiceinfoMapper.insertInfos(infos);//票据详情表插入退款账单详情
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
        return result;
    }


    /**
     *  所有账单根据业主与租户的Id
     * */
    public List<ChargeBills> getChargeBillsAll(Page<ChargeBills> page, ChargeBills chargeBills){
        List<ChargeBills> listAll = new ArrayList<ChargeBills>();
        if(StringUtils.isEmpty(chargeBills.getZjCny())){
            chargeBills.setZjCny(DateUtils.getDate("yyyy-MM"));
        }
        if(chargeBills.getDisStates() != null && chargeBills.getDisStates().size() > 0) {
            for (String stats : chargeBills.getDisStates()) {
                chargeBills.setDisState(stats);
                List<ChargeBills> list = chargeBillsMapper.getChargeBillsAll(page, chargeBills);
                listAll.addAll(list);
            }
        }else{
            listAll = chargeBillsMapper.getChargeBillsAll(page, chargeBills);
        }
        if(listAll.size() > 0){
            for (ChargeBills bills : listAll){
                List<ChargeBills> children = new ArrayList<ChargeBills>();
                List<ChargeBills> historyBills = chargeBillsMapper.selectHistoryById(bills.getId());
                if(historyBills.size() > 0){
                    for(ChargeBills history:historyBills){
                        history.setId(history.getParentBillsIds()+bills.getId());//历史账单ID与当前账单ID拼接
                        children.add(history);
                    }
                    bills.setChildren(children);
                }
            }
        }
        return  listAll;
    }

    /**
     *  所有账单根据业主与租户的Id
     * */
    public List<ChargeBills> selectBillsAll(ChargeBills chargeBills){
        List<ChargeBills> listAll = new ArrayList<ChargeBills>();
        if(StringUtils.isEmpty(chargeBills.getZjCny())){
            chargeBills.setZjCny(DateUtils.getDate("yyyy-MM"));
        }
        if(chargeBills.getDisStates() != null && chargeBills.getDisStates().size() > 0) {
            for (String stats : chargeBills.getDisStates()) {
                chargeBills.setDisState(stats);
                List<ChargeBills> list = chargeBillsMapper.selectBillsAll(chargeBills);
                listAll.addAll(list);
            }
            Collections.sort(listAll, new Comparator<ChargeBills>() {
                @Override
                public int compare(ChargeBills o1, ChargeBills o2) {
                    return o2.getZjCny().compareTo(o1.getZjCny());
                }
            });
        }else{
            listAll = chargeBillsMapper.selectBillsAll(chargeBills);
        }

        return  listAll;
    }

    /**
     *  查询合并收费的账单业主或者租户
     * */
    @Override
    public List<ChargeBills> getByRoomBillss(ChargeBills chargeBills){
        return chargeBillsMapper.getByRoomBillss(chargeBills);
    }


    /**
     *  账单拆分
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> splitBills(ChargeBills chargeBills){
        LoginUser loginUser = SsoUtil.getLoginUser();
        ChargeBills utilBills = chargeBillsMapper.get(chargeBills.getId());
        Integer maxBillsNum = chargeBillsMapper.getMaxBillsNum(utilBills);
        List<ChargeBills> splitBillList = new ArrayList<>();
        for (String money : chargeBills.getSplitMoney()){
            maxBillsNum++;
            ChargeBills splitBill = new ChargeBills();
            BeanUtils.copyProperties(utilBills,splitBill);
            splitBill.setId(null);
            splitBill.setTenantId(null);
            splitBill.setDue(new BigDecimal(money));
            splitBill.setBillsExp("拆分");
            splitBill.setZjBdrq(new Date());
            splitBill.setCreateBy(loginUser.getId());
            splitBill.setCreateTime(new Date());
            splitBill.setParentBillsIds(utilBills.getId());
            splitBill.setUpdateBy(loginUser.getId());
            splitBill.setUpdateTime(new Date());
            splitBill.setBillsNum(maxBillsNum);
            splitBillList.add(splitBill);
        }
        if (splitBillList.size() > 0 ){
            this.removeById(chargeBills.getId());
            ChargeBillsHistory chargeBillsHistory = new ChargeBillsHistory();
            BeanUtils.copyProperties(utilBills,chargeBillsHistory);
            chargeBillsHistory.setBillsExp("原账单");
            chargeBillsHistory.setTenantId(null);
            chargeBillsHistory.setUpdateBy(loginUser.getId());
            chargeBillsHistory.setUpdateTime(new Date());
            chargeBillsHistoryService.save(chargeBillsHistory);
            this.saveBatch(splitBillList);
            return Result.ok("拆分成功");
        }
        return Result.error("拆分失败");
    }

    /**
     * 退票
     *
     * */
    public String openInvoiceInfo(ChargeInvoice chargeInvoice){
        ChargeInvoice  inv = chargeInvoiceMapper.getInvoiceDmHm(chargeInvoice.getInvoiceHm(),chargeInvoice.getInvoiceDm());
        Integer result=0;
        Integer insertResult = 0;
        if(inv != null){
            List<ChargeInvoiceInfo> infoList = chargeInvoiceinfoMapper.getInvoiceInfo(inv.getId());
            insertResult = chargeInvoiceMapper.insertInvoice(inv);
            if(insertResult > 0){ //判断票据是否保存成功
                ChargeInvoice invs = new ChargeInvoice();
                invs.setInvoiceHm(inv.getInvoiceHm());
                invs.setInvoiceDm(inv.getInvoiceDm());
                result = chargeInvoiceMapper.insert(invs);
                Integer resultdelete = chargeInvoiceMapper.deleteById(inv.getId());
                if(result > 0 && resultdelete > 0){//判断票据是否还原成功
                    Integer resultinfos = chargeInvoiceinfoMapper.insertInfosRemove(infoList);
                    if(resultinfos > 0){ //判断票据详情是否保存成功
                        Integer resultDelete = 0;
                        for(ChargeInvoiceInfo info: infoList){
                            resultDelete += chargeInvoiceinfoMapper.deleteById(info.getId());
                        }
                        if(resultDelete > 0){//判断票据详情是否删除
                            List<ChargeBills>  billsList = chargeBillsMapper.getBillsByInvoiceNo(inv.getInvoiceHm(),inv.getInvoiceDm());
                            if(billsList.size() > 0){//判断是否查询到账单
                                Integer resultBills = 0;
                                for(ChargeBills bills : billsList){
                                    bills.setZjSkrq(null);
                                    bills.setPayuserName(null);
                                    bills.setInvoiceGrnno(null);
                                    bills.setInvoiceNo(null);
                                    bills.setPayType(null);
                                    bills.setMakeinvoiceDate(null);
//                                    bills.setTransactionOrder(null);
                                    bills.setBillsExp(null);
                                    bills.setRemarks(null);
                                    bills.setIncome(null);
                                    bills.setTaxPaid(0.0);
                                    bills.setTaxRate(0.0);
                                    resultBills +=  chargeBillsMapper.updateInvoiceBills(bills);
                                }
                                if(resultBills <= 0){
                                    return "操作失败，请查看账单修改失败！";
                                }
                            }
                        }else{
                            return "操作失败，请查看票据详情作废失败！";
                        }
                    }else{
                        return "操作失败，请查看票据详情保存失败！";
                    }
                }else{
                    return "操作失败，请查看票据还原失败! ";
                }
            }else{
                return "操作失败，请查看票据保存失败!";
            }
            return "操作成功！";
        }else{
            return "操作失败，请查看该票据编号与票据簿编号不符合!";
        }
    }

    public List<ChargeBills> findBillsPage(IPage<ChargeBills> page, ChargeBills chargeBills){
        List<ChargeBills> list = chargeBillsMapper.findBillsPage(page,chargeBills);
       if(list.size() > 0){
           for (ChargeBills bills : list){
               List<ChargeBills> children = new ArrayList<ChargeBills>();
               List<ChargeBills> historyBills = chargeBillsMapper.selectHistoryById(bills.getId());
               if(historyBills.size() > 0){
                   for(ChargeBills history:historyBills){
                       history.setId(history.getParentBillsIds()+bills.getId());//历史账单ID与当前账单ID拼接
                       children.add(history);
                   }
                   bills.setChildren(children);
               }
           }
       }
        return list;
    }

    public List<ChargeCollect> getDayCollect(ChargeCollect chargeCollect){
        List<ChargeCollect> historyBills = chargeBillsMapper.getDayCollect(chargeCollect);

        return historyBills;
    }

    @Override
    public Integer insertListHistory(List<ChargeBills> chargeBills) {
        return chargeBillsMapper.insertListHistory(chargeBills);
    }

    @Override
    public List<ChargeBills> findByOrderId(String orderId) {
        return chargeBillsMapper.findByOrderId(orderId);
    }

    @Override
    public void deleteByOrderId(String orderId) {
        chargeBillsMapper.deleteByOrderId(orderId);
    }

    @Override
    public void insertBills(ChargeBills newBills) {
        chargeBillsMapper.insertBills(newBills);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result delete(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList){
            ChargeBills chargeBills = chargeBillsMapper.selectById(id);
            if(chargeBills==null) {
                return Result.error("系统中未查到账单,作废失败!");
            }
            if (chargeBills.getZjSkrq() != null ){
                return Result.error("已收费账单不可作废!");
            }
            ChargeBillsHistory chargeBillsHistory = new ChargeBillsHistory();
            BeanUtils.copyProperties(chargeBills,chargeBillsHistory);
            this.removeById(chargeBills.getId());
            chargeBillsHistory.setUpdateBy(SsoUtil.getLoginUser().getId());
            chargeBillsHistory.setUpdateTime(new Date());
            chargeBillsHistory.setTenantId(null);
            chargeBillsHistory.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
            chargeBillsHistoryService.save(chargeBillsHistory);
            if (StringUtils.isNotBlank(chargeBills.getTableId())){
                List<ChargeBills> list = chargeBillsMapper.findByTableId(chargeBills.getTableId(),chargeBills.getId());
                if (list.size() == 0 ){
                    feignMeterService.rollBackBillsStatus(chargeBills.getTableId(),chargeBills.getTenantId());
                }
            }
        }
        return Result.ok("作废成功");
    }

    public List<ChargeCollect> getCollarInvoice(ChargeCollect chargeCollect){
        List<ChargeCollect> historyBills = chargeBillsMapper.getCollarInvoice(chargeCollect);
        return historyBills;
    }


    public String getByfeeName(String feeCode){
        return chargeBillsMapper.getByfeeName(feeCode);
    }

    public Integer deleteHistory(String id){
        return chargeBillsMapper.deleteHistory(id);
    }

    /**
     *  根据条件查询未收账单
     * */
    public List<ChargeBills> getChargeBills(ChargeBills chargeBills){
        return chargeBillsMapper.getChargeBills(chargeBills);
    }

    public String getLastZjCny(ChargeBills chargeBills){
        return chargeBillsMapper.getLastZjCny(chargeBills);
    }

    public ChargeInvoice getBillsDetails(ChargeBills chargeBills){
        ChargeInvoice invocie = new ChargeInvoice();
        if(chargeBills != null && StringUtils.isNotEmpty(chargeBills.getInvoiceNo()) && StringUtils.isNotEmpty(chargeBills.getInvoiceGrnno())){
            List<ChargeBillsJump> billslists = chargeBillsMapper.getBillsByJump(chargeBills.getInvoiceNo(),chargeBills.getInvoiceGrnno());
            invocie = chargeInvoiceMapper.getInvoiceDmHm(chargeBills.getInvoiceNo(),chargeBills.getInvoiceGrnno());
            List<ChargeBillsJump> billsLists = new ArrayList<ChargeBillsJump>();// 账单集合
            for (ChargeBillsJump bills : billslists) {
                String cny = bills.getZjCny();
                String billsid = bills.getId();
                bills.setNum(1);
                boolean flag = false;
                for (ChargeBillsJump utils : billsLists) {
                    if(utils != null){
                        if (bills.getFeeitemId().equals(utils.getFeeitemId())
                                && Double.doubleToLongBits(bills.getZjJe()) == Double.doubleToLongBits(utils.getZjJe())) { // 判断是否有相同的收费项目和金额
                            billsid += "," + utils.getId();
                            cny += "," + utils.getZjCny();
                            utils.setZjCny(cny);
                            utils.setNum(utils.getNum() + 1);
                            utils.setId(billsid);
                            flag = true;
                        }
                    }
                }
                if (!flag) {
                    billsLists.add(bills);
                }
            }
            for (ChargeBillsJump billss : billsLists) {
                if(billss.getZjJe() > 0 && billss.getNum() > 0){
                    billss.setFeePrice(billss.getZjJe());
                    BigDecimal b = new BigDecimal(billss.getZjJe() * billss.getNum());
                    Double  money = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    billss.setZjJe(money);
                    if(billss.getTaxRate() != null && billss.getTaxRate() > 0){
                        BigDecimal se = new BigDecimal(money - money/(1 + billss.getTaxRate() / 100));
                        Double tax = se.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        billss.setTaxPaid(tax);
                    }
                }
                billss.setUnit("月");
                String[] zjCny = billss.getZjCny().split(",");
                StringUtils.buffSort(zjCny);
                billss.setZjCny(zjCny[0] + ">" + zjCny[zjCny.length - 1]);
                billss.setIsDay("1");
            }
            invocie.setBillsList(billsLists);
        }
        return invocie;
    }

    /**
     *  所有账单根据房间的Id
     * */
    public List<ChargeBills> getPageBillsList(Page<ChargeBills> page, ChargeBills chargeBills){
        List<ChargeBills> listAll = new ArrayList<ChargeBills>();

            listAll = chargeBillsMapper.getPageBillsList(page, chargeBills);

        return  listAll;
    }
    /**
     * 根据条件查询未收账单不分页
     * */
    public List<ChargeBills> getBillsList(ChargeBills chargeBills){
        List<ChargeBills> listAll = chargeBillsMapper.getBillsList(chargeBills);
        return  listAll;
    }
    /**
     *
     * 批量打印功能
     * */
    public List<ChargePringArea> getChargePingArea(ChargeBills chargeBills){
        List<ChargePringArea> listPringArea = new ArrayList<ChargePringArea>();
        List<ChargeBills> billsList = chargeBillsMapper.getBillsList(chargeBills);
        Map<String, List<ChargeBills>> map = new HashMap<>();
        if(/*chargeBills.getTypes().equals("2") &&*/ billsList.size() > 0){//业主
            for(ChargeBills bill : billsList){
                if(map.containsKey(bill.getCustomerId())){
                    map.get(bill.getCustomerId()).add(bill);
                }else{
                    List<ChargeBills> tmpList = new ArrayList<>();
                    tmpList.add(bill);
                    map.put(bill.getCustomerId(), tmpList);
                }
            }
        }
//        if(chargeBills.getTypes().equals("1") && billsList.size() > 0){//租户
//            for(ChargeBills bill : billsList){
//                if(map.containsKey(bill.getRentId())){
//                    map.get(bill.getRentId()).add(bill);
//                }else{
//                    List<ChargeBills> tmpList = new ArrayList<>();
//                    tmpList.add(bill);
//                    map.put(bill.getRentId(), tmpList);
//                }
//            }
//        }
        for(List<ChargeBills> bills: map.values()){
            if(bills.size() > 0){
                ChargePringArea area = new ChargePringArea();
                List<ChargeBills> billsLists = new ArrayList<ChargeBills>();
                for(ChargeBills bill:bills){
                    bill.setNum(1);
                    boolean flag = false;
                    String cny = bill.getZjCny().replaceAll("-", "/");
                    for(ChargeBills charge : billsLists){
                        if (bill.getFeeitemId().equals(charge.getFeeitemId()) && bill.getDue().compareTo(charge.getDue()) == 0) {//判断收费项目以及金额
                            cny += "," + charge.getZjCny().replaceAll("-", "/");
                            charge.setNum(charge.getNum() + 1);
                            charge.setZjCny(cny);
                            flag = true;
                        }
                    }
                    if (!flag) {
                        billsLists.add(bill);
                    }
                }
                Double sumMoney = 0.0;
                for (ChargeBills util : billsLists) {
                    String[] zjCny = util.getZjCny().split(",");
                    StringUtils.buffSort(zjCny);
                    util.setDue(util.getDue().multiply(new BigDecimal(util.getNum())).setScale(2,BigDecimal.ROUND_HALF_UP));
                    if (zjCny.length > 1) {
                        switch(zjCny.length){
                            case 1:
                                util.setZjCny(zjCny[zjCny.length - 1]);
                                break;
                            default:
                                util.setZjCny(zjCny[0]+"-"+zjCny[zjCny.length - 1]);
                                break;
                        }
                    }
                    sumMoney += util.getDue().doubleValue();
                }
                if(billsLists != null && billsLists.size() > 0){
                    area.setFloorName(billsLists.get(0).getFloorName());
                    area.setRoomName(billsLists.get(0).getRoomName());
                    area.setCrmName(billsLists.get(0).getCustomerName());
                    area.setRenName(billsLists.get(0).getRentName());
                    area.setProjectName(chargeBillsMapper.selectProjectName(billsLists.get(0).getProjectId()));
                    if(StringUtils.isNotEmpty(billsLists.get(0).getCustomerId())){
                        area.setCusPhone(chargeBillsMapper.selectCusPhone(billsLists.get(0).getCustomerId()));
                    }
                    if(StringUtils.isNotEmpty(billsLists.get(0).getRentId())){
                        area.setRenPhone(chargeBillsMapper.selectRenPhone(billsLists.get(0).getRentId()));
                    }
                    area.setSumMoney(getBigDecimal(sumMoney));
                    area.setBills(billsLists);
                 }
                listPringArea.add(area);
            }
        }
        return listPringArea;

    }

    /**
       * @param excelName
       * double计算保留两位小数
       * @return
       * @throws IOException
       */
    private Double getBigDecimal(Double sum){
        BigDecimal bigsum = new BigDecimal(sum);
        Double sums = bigsum.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return sums;
    }

    public List<ChargeBills> getChargeBillsByInvoiceId(String invoiceId){
        return  chargeBillsMapper.getChargeBillsByInvoiceId(invoiceId);
    }
}
